﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Speech.Synthesis;
using System.Threading;
using System.Windows;
using System.Xml.Linq;
using WpfApp1.bean;
using WpfApp1.CMD;
using WpfApp1.Httpwork;
using WpfApp1.mysqlunit;

namespace WpfApp1.Main
{
    class MainM : InterfacePackage,HttpDeleteZupanInterface, HttpPostZupanInterface,HttpGetPallectData
    {
        List<string> batchs;
        Dictionary<String, packagebean> packages;
        Dictionary<String, packagebean> cunpackages;
        Dictionary<String, panbean> panonum;
        public String[] buffers = {};
        ArrayList chuankous = new ArrayList();
        //List<string> categorys;
        MysqlData mysqldata;
        myCom mycom;
        MainInterface M;
        SpeechSynthesizer synthesizer;
        String AP = "";
        public MainM(MainInterface interfac, List<string> batchs, Dictionary<String, packagebean> packages, Dictionary<String, panbean> panonum, ArrayList chuankous, String[] buffers, myCom mycom)
        {
            M = interfac;
            this.batchs = batchs;
            this.packages = packages;
            this.panonum = panonum;
            this.chuankous = chuankous;
            //this.categorys = categorys;
            cunpackages = new Dictionary<String, packagebean>();
            mysqldata = MysqlData.createMysqlData();
            this.buffers = buffers;
            this.mycom = mycom;
            synthesizer = new SpeechSynthesizer();
            synthesizer.Volume = 100;
            
            cleanCom();
        }

        public void setRate(int rate)   
        {
            synthesizer.Rate = rate;
        }
        
        public void setAP(String AP)
        {
            this.AP = AP;
        }

        //读取需要下载的节号
        public void readbatch()
        {
            mysqldata.readbatch(batchs);
        }


        public void readpackage()
        {
            mysqldata.readpackage(packages);
        }

        //读取包缓存文件
        public void readbaoXXL()
        {
                //读取位置处的盘
            mysqldata.readpanonym(panonum);
            if (panonum.Count == 0)
            {
                for (var i = 0; i < buffers.Length; i++)
                {
                    var bean = new panbean();
                    bean.buffer = buffers[i];
                    bean.onum = "";
                    bean.pallet = "";
                    panonum.Add(buffers[i], bean);
                }
                firstWritPan();
            }
            //读取需要下载的节号
            readbatch();

            //查询未组盘的包
            mysqldata.cleanPackage(batchs);
            mysqldata.readpackage(packages);
            M.cleanView();
        }

        /**写入设置的缓冲仓位*/
        public void cleanbuffer()
        {
            if (buffers.Length == 12)
            {
                for (var i = 0; i < 12; i++)
                {
                    mysqldata.writeBuffer(i+1, buffers[i]);
                }
                panonum.Clear();
                mysqldata.readpanonym(panonum);
            }
            
        }

        //网络访问获取节号数据
        public void HttpHuoquJiehao()
        {
            
            readbatch();

            if (batchs.Count == 0)
            {
                return;
            }
            M.cleanOperation("正在访问服务器按照设置的物料类别和节号获取包数据",false);
            //Http.getHttp_Batch_Package(this, this.pcode, categorys);
            Http.getHttpPackage(this, batchs);

        }

       

        //将数据写入缓存文件
        //public void writdata()
        //{
        //    writsqldata();
        //}
        //第一次写入空的盘数据
        public void firstWritPan()
        {
            mysqldata.firstwritePan(panonum);
        }
        //将数据写入数据库
        //public void writsqldata()
        //{
        //    writsqlpans();
        //    writSqlPackages();
        //}
        //将所有盘数据写入数据库
        public void writsqlpans()
        {
            foreach (KeyValuePair<String, panbean> p in panonum)
            {
                mysqldata.writePan(p.Value);
            }
        }

        //将扫描日志写入数据库
        public void writerizhi(string scan_string, string describe)
        {
            mysqldata.write_scan_record(scan_string,describe);
        }
        
        //将所有包数据写入数据库
        public void writSqlPackages()
        {
            mysqldata.writePackages(packages);
            mysqldata.readbatch(batchs);
        }

        //修改托盘数据
        public void writsqlpan(panbean bean)
        {
            mysqldata.writePan(bean);
        }

        //修改托包数据
        public void writSqlPackage(packagebean bean)
        {
            mysqldata.writePackage(bean);
        }

        //点击添加节号
        public void addJiehao(String b)
        {
            String batch = b;
            if (batchs.Contains(batch))
            {
                MessageBox.Show("节号列表中已有该节号");
            }
            else
            {
                M.cleanOperation("正在访问服务器获取节号包内容",false);
                List<String> listbatch = new List<String>();
                listbatch.Add(batch);
                Http.getHttpPackage(this, listbatch);
                //Http.getHttpPackage(this, listbatch, null, categorys);
            }
        }


        //点击删除节号
        public void removeJiehao(String b)
        {
            String batch = b;
            if (!batchs.Contains(batch))
            {
                MessageBox.Show("该节号不在列表中");
            }
            else
            {
                if (isbatchafenpei(batch))
                {
                    MessageBox.Show("该节号已经有包组盘，不能删除");
                }
                else
                {
                    foreach (KeyValuePair<String, packagebean> p in packages)
                    {
                        if (p.Value.batch == batch)
                        {
                            packages.Remove(p.Key);
                        }
                    }
                    batchs.Remove(batch);
                    mysqldata.deletebatch(batch);
                    //HttpHuoquJiehao();
                }
            }
            
        }

        //判断这个盘是否分配
        private Boolean isbatchafenpei(String batch)
        {
            var b = false;
            foreach (KeyValuePair<String, packagebean> p in packages)
            {
                var bean = p.Value;
                if (bean.batch == batch && bean.pallet_id != "0")
                {
                    b = true;
                }
            }
            return b;
        }

        //解析网络访问获取结节号数据json字符串
        public void json(String data)
        {
            if (data == "")
            {
                return;
            }
            cunpackages.Clear();
            foreach (KeyValuePair<String, packagebean> p in packages)
            {
                cunpackages.Add(p.Key, p.Value);
            }
            var jsonarray = (JArray)JsonConvert.DeserializeObject(data);
            var listpackage = new Dictionary<String, packagebean>();
            foreach (JObject jo in jsonarray)
            {

                if (cunpackages.ContainsKey((String)jo["pcode"]))
                {

                    packagebean bean = cunpackages[(String)jo["pcode"]];
                    bean.deliver_time = (String)jo["deliver_time"];
                    bean.warehousing_time = (String)jo["warehousing_time"];
                    bean.pallet_num = (String)jo["pallet_num"];
                    packages[(String)jo["pcode"]] = bean;
                    listpackage[(String)jo["pcode"]] = bean;

                }
                else
                {
                    packagebean bean = new packagebean();
                    bean.batch = (String)jo["batch_name"];
                    bean.pid = (String)jo["pid"];
                    bean.pcode = (String)jo["pcode"];
                    bean.onum = (String)jo["onum"];
                    bean.deliver_time = (String)jo["deliver_time"];
                    bean.warehousing_time = (String)jo["warehousing_time"];
                    bean.pallet_num = (String)jo["pallet_num"];
                    bean.pallet_id = "0";
                    packages[(String)jo["pcode"]] = bean;
                    listpackage[(String)jo["pcode"]] = bean;
                }
            }
            addYiYou();
            mysqldata.writePackages(listpackage);
            mysqldata.readbatch(batchs);
            //writSqlPackages();
            M.cleanView();
        }

        //获取该单共多少包
        private int onumZPsize(String onum)
        {
            int size = 0;
            foreach (KeyValuePair<String, packagebean> p in packages)
            {
                packagebean bean = p.Value;
                if (bean.onum == onum )
                {
                    
                    if (bean.pallet_id == "0" && bean.pallet_num != "")
                    {
                        continue;
                    }
                    size++;
                }
            }
            return size;
        }

        //如果包数小于或等于二，前往AP盘
        public void shuaixuanAP(packagebean bean, Boolean isZiDong)
        {
            if (bean.pallet_id == "0" && bean.pallet_num != "")
            {
                MessageBox.Show("该包已经完成组盘，不能再次组盘");
                return;
            }
            int count = onumZPsize(bean.onum);
            if (count > 2 || AP == "")
            {
                fenpei(bean, isZiDong);
            }
            else
            {
                setAP(bean);
            }
        }

        //分配到AP盘上去
        public void setAP(packagebean bean)
        {
            packages[bean.pcode].pallet_id = AP;
            writSqlPackage(packages[bean.pcode]);
            M.cleanOperation("将包条码" + bean.pcode + "分配到" + AP + "托盘",false);
            writerizhi(bean.pcode, "将包条码" + bean.pcode + "分配到" + AP + "托盘" + panonum[AP].pallet);
            M.cleanView();
            ArrayList arr = new ArrayList(buffers);
            var pan = arr.IndexOf(AP) + 1;
            mycom.RedLight(pan);
            M.alter_backgrounf(pan);
            synthesizer.SpeakAsync(pan+"号");
            synthesizer.SpeakAsync(pan+"号");
        }

        //public void bofang()
        //{
        //   
        //    synthesizer.SpeakAsync("1号");
        //}

        //分配包到盘上
        public void fenpei(packagebean bean, Boolean isZiDong)
        {

            String onum = bean.onum;
            if (bean.pallet_id == "0" || bean.pallet_id == AP)
            {
                var pan = getpanonum(bean.onum);
                if (pan == "0")
                {
                    var kongpan = kongpanonum();
                    if (kongpan != "0")
                    {
                        if (isZiDong)
                        {
                            packages[bean.pcode].pallet_id = kongpan;
                            panonum[kongpan].onum = bean.onum;
                            writSqlPackage(packages[bean.pcode]);
                            writsqlpan(panonum[kongpan]);
                            M.cleanOperation("此单号未配," + "将包条码" + bean.pcode + "分配到" + kongpan + "号托盘",false);
                            writerizhi(bean.pcode, "此单号未配," + "将包条码" + bean.pcode + "分配到" + kongpan + "号托盘" + panonum[kongpan].pallet);
                            M.cleanView();
                            ArrayList arr = new ArrayList(buffers);
                            var ph = arr.IndexOf(kongpan) + 1;
                            M.alter_backgrounf(ph);
                            mycom.RedLight(ph);
                            synthesizer.SpeakAsync(ph + "号");
                            synthesizer.SpeakAsync(ph + "号");
                        }
                        else
                        {
                            if (MessageBox.Show("此单号未配，" + "将自动分配到" + kongpan + "号托盘", "确定分配包", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                            {
                                packages[bean.pcode].pallet_id = kongpan;
                                panonum[kongpan].onum = bean.onum;
                                writSqlPackage(packages[bean.pcode]);
                                writsqlpan(panonum[kongpan]);
                                M.cleanOperation("此单号未配," + "将包条码" + bean.pcode + "分配到" + kongpan + "号托盘",false);
                                writerizhi(bean.pcode, "此单号未配," + "将包条码" + bean.pcode + "分配到" + kongpan + "号托盘"+ panonum[kongpan].pallet);
                                M.cleanView();
                                ArrayList arr = new ArrayList(buffers);
                                var ph = arr.IndexOf(kongpan) + 1;
                                M.alter_backgrounf(ph);
                                mycom.RedLight(ph);
                                synthesizer.Volume = 100;
                                synthesizer.SpeakAsync(ph + "号");
                                synthesizer.SpeakAsync(ph + "号");
                            }
                        }

                    }
                    else
                    {
                        M.cleanOperation("此单号尚未分配托盘，并且没有空托盘，暂时不能分配",true);
                        writerizhi(bean.pcode, "此单号尚未分配托盘，并且没有空托盘，暂时不能分配");
                        //MessageBox.Show("此单号尚未分配托盘，并且没有空托盘，暂时不能分配");
                    }
                }

                else
                {
                    if (isZiDong)
                    {
                        packages[bean.pcode].pallet_id = pan;
                        writSqlPackage(packages[bean.pcode]);
                        M.cleanOperation("将包条码" + bean.pcode + "分配到" + pan + "号托盘",false);
                        writerizhi(bean.pcode, "将包条码" + bean.pcode + "分配到" + pan + "号托盘" + panonum[pan].pallet);
                        M.cleanView();
                        ArrayList arr = new ArrayList(buffers);
                        var ph = arr.IndexOf(pan) + 1;
                        mycom.RedLight(ph);
                        M.alter_backgrounf(ph);
                        rucang(onum,pan);
                        synthesizer.SpeakAsync(ph + "号");
                        synthesizer.SpeakAsync(ph + "号");
                    }
                    else
                    {
                        if (MessageBox.Show("确定组盘" + bean.pcode + "吗？将会分配到" + pan + "号托盘", "标题", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                        {
                            packages[bean.pcode].pallet_id = pan;
                            writSqlPackage(packages[bean.pcode]);
                            M.cleanOperation("将包条码" + bean.pcode + "分配到" + pan + "号托盘",false);
                            writerizhi(bean.pcode, "将包条码" + bean.pcode + "分配到" + pan + "号托盘" + panonum[pan].pallet);
                            M.cleanView();
                            ArrayList arr = new ArrayList(buffers);
                            var ph = arr.IndexOf(pan) + 1;
                            mycom.RedLight(ph);
                            M.alter_backgrounf(ph);
                            rucang(onum,pan);
                            synthesizer.SpeakAsync(ph + "号");
                            synthesizer.SpeakAsync(ph + "号");
                        }
                    }

                }

            }
            else
            {
                writerizhi(bean.pcode, "已经在托盘上，再次闪灯");
                ArrayList arr = new ArrayList(buffers);
                var pan = arr.IndexOf(bean.pallet_id) + 1;
                M.alter_backgrounf(pan);
                mycom.RedLight(pan);
                synthesizer.SpeakAsync(pan + "号");
                synthesizer.SpeakAsync(pan + "号");

             }

        
        }

        /**移出组盘，判断包是否已经组盘，如果已经组盘，则询问是否移出，如果没有组盘，则直接改数据
         * bean:想要移出组盘的包
         */
        public void yichu_zupan(packagebean bean)
        {
            if (bean.pallet_num != "")
            {
                if (MessageBox.Show(bean.pcode + "已经组盘，确定将包从盘" + panonum[bean.pallet_id].pallet + "中移除吗？", "标题", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                {
                    writerizhi(bean.pcode, "将包条码" + bean.pcode + "从托盘移除");
                    Http.deleteZupan(this, bean);

                }
            }
            else
            {
                writerizhi(bean.pcode, "将包条码" + bean.pcode + "从托盘移除");
                M.cleanOperation("将包条码" + bean.pcode + "移动到未组盘区",false);
                packages[bean.pcode].pallet_id = "0";
                writSqlPackage(packages[bean.pcode]);
                M.cleanView();
            }
        }

        /**组盘后判断本单是否全部组完，组盘则自动入仓移盘
         * onum : 刚组包的单号
         */
        private void rucang(String onum,String pan) {
            if (iszuwan(onum,pan))
            {
                ArrayList pcodes = new ArrayList();
                zupan zu = new zupan();
                string content = "";
                zu.position_buffer = pan;
                zu.height = "800mm";
                zu.pallet_num = panonum[pan].pallet;


                zu.confirm_code = 0;
                foreach (KeyValuePair<String, packagebean> p in packages)
                {
                    var package = p.Value;
                    if (package.pallet_id == pan)
                    {
                        pcodes.Add(package.pcode);
                    }
                }
                zu.pcodes = pcodes;

                content = JsonConvert.SerializeObject(zu);

                Console.WriteLine(content);
                Http.PostZupan(this, content, pan);
            }
        }


        /**判断数据中本包的单是否全部组完*/
        private Boolean iszuwan(String onum,String pan)
        {
            
            foreach (KeyValuePair<String, packagebean> p in packages)
            {
                if ((p.Value.pallet_id == "0" && p.Value.onum == onum && p.Value.pallet_num.Length == 0) || panonum[pan].pallet == "")
                {
                    return false;
                }
            }
            foreach (KeyValuePair<String, packagebean> p in packages)
            {
                if (p.Value.onum == onum && p.Value.pallet_id == AP && p.Value.pallet_num.Length == 0)
                {
                    if (MessageBox.Show("这个单在AP托盘里有包存在，现在提交吗？" , "提示", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                    
                }
            }

            return true;
        }

        //查看单号属于哪个盘writerizhi
        private String getpanonum(String onum)
        {
            
            var ispan = "0";
            foreach (KeyValuePair<String, panbean> p in panonum)
            {
                if (onum == p.Value.onum && p.Value.buffer != AP)
                {
                    ispan = p.Key;
                }
            }
            return ispan;
        }

        //判断是否有空盘,如果有则返回盘，没有则返回0
        private String kongpanonum()
        {
            var pan = "0";
            foreach (KeyValuePair<String, panbean> p in panonum)
            {
                if (p.Value.onum == "" && p.Value.pallet != "")
                {
                    pan = p.Key;
                    break;
                }
            }
                Console.WriteLine(pan);

            return pan;
        }

        //盘数据发送给服务器
        public void postpan(String pan)
        {
            ArrayList pcodes = new ArrayList();
            String onum = "";
            foreach (KeyValuePair<String, packagebean> p in Window1.packages)
            {
                var package = p.Value;
                if (package.pallet_id == pan)
                {
                    onum = package.onum;
                    pcodes.Add(package.pcode);
                }
            }
            if (pan != AP)
            {
                foreach (KeyValuePair<String, packagebean> p in packages)
                {
                    if (p.Value.onum == onum && p.Value.pallet_id == AP && p.Value.pallet_num.Length == 0)
                    {
                        if (MessageBox.Show("这个单在AP托盘里有包存在，现在提交吗？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                        {
                            zupalletdialog dialog = new zupalletdialog(pan);

                            var ad = dialog.ShowDialog();
                            if ((bool)ad)
                            {
                                zupan_wancheng(pan);
                            }
                            return;
                        }
                        else
                        {
                            return;
                        }

                    }
                }
            }
            
            //if (pcodes.Count == 0)
            //{
            //    MessageBox.Show("托盘没有分配包，不能上传组盘");
            //    return;
            //}
            zupalletdialog zupandialog = new zupalletdialog(pan);

            var a = zupandialog.ShowDialog();
            if ((bool)a)
            {
                zupan_wancheng(pan);
            }

        }

        //判断托盘是否原本有货,有则将这些包添加到托盘
        public void addYiYou()
        {
            foreach (KeyValuePair<String, packagebean> p in packages)
            {
                if (p.Value.pallet_num == "")
                {
                    continue;
                }
                if (p.Value.batch == "")
                {
                    continue;
                }
                foreach (KeyValuePair<String, panbean> pan in panonum)
                {
                    if (pan.Value.pallet == p.Value.pallet_num )
                    {
                        p.Value.pallet_id = pan.Key;
                        writSqlPackage(p.Value);
                    }
                }
            }
        }


        String pcode = "";
        //没有下载组盘的节号，按照包条码下载节数据
        public void addPcodeBatch(String pcode)
        {
            this.pcode = pcode;
            Http.getHttp_Batch_Package(this, pcode);
        }

        /**刷新串口*/
        public void cleanCom()
        {
            mycom.readCOMs(true);
        }

        //获取到包数据
        public void setPackage(string data , Boolean isclean)
        {
            if (isclean)
            {
                List<string> otherStus = new List<string>();
   
                foreach (KeyValuePair<String, packagebean> p in packages)
                {
                    var package = p.Value;
                    if (package.pallet_id == "0")
                    {
                        otherStus.Add(p.Key);
                    }
                }
                for (int i = 1; i < otherStus.Count; i++)
                {
                    packages.Remove(otherStus[i]);
                }

            }
            json(data);

        }

        public void setBaoPackage(String data, Boolean isclean, String pcode)
        {
            json(data);
            if (packages.ContainsKey(pcode))
            {
                var package = packages[pcode];
                shuaixuanAP(package, true);
            }
        }

        //组盘时查询托盘组盘数据
        public void getPalletdata(String pallet,int pan)
        {
            Http.getPallectData(this,pallet,pan);
        }

        public void setError(string e)
        {
            if (MessageBox.Show(e, "错误", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
            {

            }
        }

        public void httpDeleteZupanOk(packagebean bean)
        {
            M.cleanOperation("将包条码" + bean.pcode + "移动到未组盘区",false);
            packages[bean.pcode].pallet_id = "0";
            writSqlPackage(packages[bean.pcode]);
            M.cleanView();
            Http.getHttpPackage(this, batchs);
        }

        public void httpDeleteZupanNo(string e, bool b)
        {
            if (MessageBox.Show(e, "错误", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
            {

            }


        }


        public void httpPostZupanOk(string data, string pan)
        {
            JObject obj = JObject.Parse(data);
            string status = (String)obj["status"];
            string s = (String)obj["msg"];
            if (status == "success")
            {
                Console.WriteLine("url===================" + status);
                zupan_wancheng(pan);
            }
            else
            {
                MessageBox.Show(s);
            }

        }


        /**组盘完成处理*/
        public void zupan_wancheng(String pan)
        {

            Http.finish_zupan(this, panonum[pan].pallet);
            foreach (KeyValuePair<String, packagebean> p in packages)
            {
                var package = p.Value;
                if (package.pallet_id == pan)
                {
                    package.pallet_id = "0";
                    writSqlPackage(package);
                }
            }
            
            var panbean = new panbean();
            panbean.buffer = pan;
            panbean.onum = "";
            panbean.pallet = "";
            panonum[pan] = panbean;
            writsqlpan(panbean);
            //writdata();
            M.cleanOperation(pan + "号托盘组盘数据已经成功上传服务器，现在将" + pan + "号托盘拖走",false);
            ArrayList arr = new ArrayList(buffers);
            var panhao = arr.IndexOf(pan) + 1;
            mycom.GreenLight(panhao);
            M.zpbt_backgrounf(panhao , false);
            M.cleanView();

            foreach (string batch in batchs)
            {
                string package = "";
                foreach (KeyValuePair<String, packagebean> p in packages)
                {
                    packagebean bean = p.Value;
                    if (batch == bean.batch && bean.warehousing_time == "" && bean.deliver_time == "")
                    {
                        package = package + bean.pcode;
                    }
                }
                if (package == "")
                {
                    batchs.Remove(batch);
                    break;
                }
            }
            HttpHuoquJiehao();
        }

        public void httpPostZupanNo(string e, bool b)
        {
            MessageBox.Show(e);
        }

        public void setFinishPackageOK(string data)
        {
        }

        public void setFinishPackageNo(string e)
        {
            MessageBox.Show(e);
        }

        public void getPallectDataOk(String data, int pan)
        {
            var jo = (JObject)JsonConvert.DeserializeObject(data);
            var js = (JArray)jo["data"];
            foreach (JObject o in js)
            {
                M.zpbt_backgrounf(pan,true);
                return;
            }
            M.zpbt_backgrounf(pan, false);
        }
        public void getPallectDataNo(String e, Boolean b)
        {

        }
    }
}
